package com.transpeed.payservice.resultHandler;

import java.lang.reflect.Field;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.List;

/**
 * @author zhuli 结果集处理类
 */
public class BeanHandler implements IResultSetHandler {
	// 通配泛型
	private Class<?> clazz;

	public BeanHandler(Class<?> clazz) {
		this.clazz = clazz;
	}

	// 结果集转bean
	@Override
	public Object beanHandler(ResultSet rs) {
		// TODO Auto-generated method stub
		try {
			if (!rs.next()) {
				return null;
			}
			Object bean = clazz.newInstance();
			// 得到结果集数据
			ResultSetMetaData metdata = rs.getMetaData();
			// 结果集列数
			int columnCount = metdata.getColumnCount();
			for (int i = 0; i < columnCount; i++) {
				// 得到列名
				String columnName = metdata.getColumnName(i + 1);
				Object columnData = rs.getObject(i + 1);
				// 反射出类上列名对应的属性
				Field f = clazz.getDeclaredField(columnName);
				f.setAccessible(true);
				f.set(bean, columnData);
			}
			return bean;
		} catch (Exception e) {
			throw new RuntimeException(e);
		}

	}

	// 结果集转bean的List集合
	@Override
	public List<Object> listHandler(ResultSet rs) {
		// TODO Auto-generated method stub
		List<Object> list = new ArrayList<Object>();
		try {
			while (rs.next()) {
				Object bean = clazz.newInstance();
				// 得到结果集数据
				ResultSetMetaData metadata = rs.getMetaData();
				int columnCount = metadata.getColumnCount();

				for (int i = 0; i < columnCount; i++) {
					// 得到列名
					String columnName = metadata.getColumnName(i + 1);
					Object columnData = rs.getObject(columnName);
					// 反射出类上列名对应的属性
					Field f = clazz.getDeclaredField(columnName);
					f.setAccessible(true);
					f.set(bean, columnData);
				}

				list.add(bean);
			}
			return list.size() > 0 ? list : null;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			throw new RuntimeException(e);
		}

	}
}
